import React, { Component } from 'react';
import { Icon, Input, Button, Table, message, Popconfirm } from 'antd';
import CodeEditor from './Ace/index';
import './index.less';
import store from '../../redux/index';
import axios from 'axios';
const Search = Input.Search;

class Contract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      result: '',
      codeOff: store.getState().Contract.SetCodeOff,
      pagination: {
        current: 1,
        defaultCurrent: 1,
        total: 0,
        onChange: this.pageChange
      },
      SearchName: ''
    };
  }
  pageChange = (page) => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    $this.state.pagination.current = page;
    axios({
      method: 'get',
      url: '/api/admin/chaincode/management/queryChainCodes',
      headers: {
        Authorization: Token
      },
      params: {
        page: page,
        limit: 10,
        chainCodeName: $this.state.SearchName
      }
    })
      .then(function (response) {
        let Data = [];
        $this.state.pagination.total = response.data.data.total;
        if (response.data.data.rows.length !== 0) {
          response.data.data.rows.forEach((item, i) => {
            if (item.templateId == '0') {
              item.templateId = '自建模板';
            } else {
              item.templateId = '模板chainCode';
            }
            if (item.codeStatus == '1000') {
              item.codeStatus = '安装中';
            } else if (item.codeStatus == '1010') {
              item.codeStatus = '安装成功';
            } else if (item.codeStatus == '1020') {
              item.codeStatus = '安装失败';
            } else if (item.codeStatus == '2000') {
              item.codeStatus = '部署中';
            } else if (item.codeStatus == '2010') {
              item.codeStatus = '部署成功';
            } else if (item.codeStatus == '2020') {
              item.codeStatus = '部署失败';
            } else if (item.codeStatus == '3000') {
              item.codeStatus = '升级中';
            }
            Data.push({
              'key': item.id,
              'id': item.id,
              'channelcodename': item.channelcodename,
              'channelversion': item.channelversion,
              'templateId': item.templateId,
              'codeStatus': item.codeStatus,
              'crtTime': item.crtTime,
              'nickName': item.nickName,
              'orgName': item.orgName,
              'name': item.name,
              'channelcodepath': item.channelcodepath
            });
          });
          $this.setState({
            data: Data
          });
        }
      })
      .catch(function (error) {
        message.error('请求失败，请稍后重试');
      });
  }
  componentWillReceiveProps(nextProps) {
    if (store.getState().Contract.SetCodeOff) {
      return false;
    } else {
      this.setState({
        codeOff: false
      });
    }
  }
  getContract = () => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    $this.state.SearchName = '';
    axios({
      method: 'get',
      url: '/api/admin/chaincode/management/queryChainCodes',
      headers: {
        Authorization: Token
      },
      params: {
        page: 1,
        limit: 10
      }
    }).then(function (response) {
      let Data = [];
      $this.state.pagination.total = response.data.data.total;
      if (response.data.data.rows.length !== 0) {
        response.data.data.rows.forEach((item, i) => {
          if (item.templateId == '0') {
            item.templateId = '自建模板';
          } else {
            item.templateId = '模板chainCode';
          }
          if (item.codeStatus == '1000') {
            item.codeStatus = '安装中';
          } else if (item.codeStatus == '1010') {
            item.codeStatus = '安装成功';
          } else if (item.codeStatus == '1020') {
            item.codeStatus = '安装失败';
          } else if (item.codeStatus == '2000') {
            item.codeStatus = '部署中';
          } else if (item.codeStatus == '2010') {
            item.codeStatus = '部署成功';
          } else if (item.codeStatus == '2020') {
            item.codeStatus = '部署失败';
          } else if (item.codeStatus == '3000') {
            item.codeStatus = '升级成功待部署';
          }
          Data.push({
            'key': item.id,
            'id': item.id,
            'channelcodename': item.channelcodename,
            'channelversion': item.channelversion,
            'templateId': item.templateId,
            'codeStatus': item.codeStatus,
            'crtTime': item.crtTime,
            'nickName': item.nickName,
            'orgName': item.orgName,
            'name': item.name,
            'channelcodepath': item.channelcodepath
          });
        });
        $this.setState({
          data: Data
        });
      }

    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });
  }
  // 下载
  downloadGo = (Path) => {
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/blockchaincode/downloadChaincode',
      headers: {
        Authorization: Token
      },
      params: {
        path: Path
      }
    }).then(function (response) {
      window.open('/api/admin/blockchaincode/downloadChaincode?path=' + Path + '&token=' + Token);
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });
  }
  // 条件搜索
  searchUser = (value) => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    $this.state.SearchName = value;
    $this.state.pagination.current = 1;
    axios({
      method: 'get',
      url: '/api/admin/chaincode/management/queryChainCodes',
      headers: {
        Authorization: Token
      },
      params: {
        chainCodeName: value
      }
    }).then(function (response) {
      let Data = [];
      $this.state.pagination.total = response.data.data.total;
      if (response.data.data.rows.length !== 0) {
        response.data.data.rows.forEach((item, i) => {
          if (item.templateId == '0') {
            item.templateId = '自建模板';
          } else {
            item.templateId = '模板chainCode';
          }
          if (item.codeStatus == '1000') {
            item.codeStatus = '安装中';
          } else if (item.codeStatus == '1010') {
            item.codeStatus = '安装成功';
          } else if (item.codeStatus == '1020') {
            item.codeStatus = '安装失败';
          } else if (item.codeStatus == '2000') {
            item.codeStatus = '部署中';
          } else if (item.codeStatus == '2010') {
            item.codeStatus = '部署成功';
          } else if (item.codeStatus == '2020') {
            item.codeStatus = '部署失败';
          } else if (item.codeStatus == '3000') {
            item.codeStatus = '升级成功待部署';
          }
          Data.push({
            'key': item.id,
            'id': item.id,
            'channelcodename': item.channelcodename,
            'channelversion': item.channelversion,
            'templateId': item.templateId,
            'codeStatus': item.codeStatus,
            'crtTime': item.crtTime,
            'nickName': item.nickName,
            'orgName': item.orgName,
            'name': item.name,
            'channelcodepath': item.channelcodepath
          });
        });
        $this.setState({
          data: Data
        });
      }
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });

  }
  componentWillMount() {
    this.getContract();
  }
  preview = (Path) => {
    const $this = this;
    const Token = sessionStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/admin/chaincode/management/downloadInputStream?path=' + Path,
      headers: {
        Authorization: Token
      },
    }).then(function (response) {
      store.dispatch({ type: 'SetCodeOff', SetCodeOff: true });
      let SetCodeOff = store.getState().Contract.SetCodeOff;
      $this.setState({
        result: response.data,
        codeOff: SetCodeOff
      });
      console.log(document.getElementsByTagName('body'));
      document.getElementsByTagName('body')[0].className = document.getElementsByTagName('html')[0].className = 'hidden';
      // document.getElementsByTagName('html')[0].className = 'hidden';
    }).catch(function (error) {
      message.error('请求失败，请稍后重试');
    });
  }
  render() {
    const columns = [{
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    }, {
      title: '名称',
      dataIndex: 'channelcodename',
      key: 'channelcodename',
    },
    {
      title: '版本',
      dataIndex: 'channelversion',
      key: 'channelversion',
    }, {
      title: '类型',
      dataIndex: 'templateId',
      key: 'templateId',
    }, {
      title: '状态',
      dataIndex: 'codeStatus',
      key: 'codeStatus',
    }, {
      title: '安装时间',
      dataIndex: 'crtTime',
      key: 'crtTime',
    }, {
      title: '安装网络',
      dataIndex: 'nickName',
      key: 'nickName',
    }, {
      title: '所属组织',
      dataIndex: 'orgName',
      key: 'orgName',
    },
    {
      title: '安装用户',
      dataIndex: 'name',
      key: 'name',
    }, {
      title: '操作',
      key: '操作',
      width: '10%',
      render: (text, record) => (
        <span className="operation">
          <a onClick={() => this.preview(record.channelcodepath)}>预览代码</a>
          <a className="download" onClick={() => this.downloadGo(record.channelcodepath)}>下载</a>
        </span>
      ),
    }];
    return (
      <div>
        <div className="index-buttons">
          <Search placeholder="Chaincode名称" onSearch={value => this.searchUser(value)} enterButton size="large" style={{ width: 330 }} />
        </div>
        <Table columns={columns} dataSource={this.state.data} rowKey="id" bordered pagination={this.state.pagination} />
        {
          this.state.codeOff ? <CodeEditor
            className="CodeEditor"
            result={this.state.result}
          ></CodeEditor>
          : ''
        }
      </div>


    );
  }
}

export default Contract;
